<?php 
namespace Home\Controller;
use \Think\Controller;

//个人中心控制器
class PersController extends Controller
{
    //控制打开个人中心
    public function index()
    {
        // 实例化用户扩展信息并获取头像信息,必须登录才可以进入个人中心页面
        if (!empty($_SESSION['user'])) {

            // 如果GET中的uid有数据说明是访问别人的个人中心,此时user_id应该为$_GET中的uid,并且不可以修改资料上传头像
            if (empty($_GET['uid']) || $_GET['uid'] ===$_SESSION['user']['uid'] ) {
                $uid = $_SESSION['user']['uid'];
                // 定义askPage变量方便判断访问状态
                $this->assign('askPage','my');
            } else{
                $uid = $_GET['uid'];
                $uid = I('get.uid/d');
                // 定义askPage变量方便判断访问状态
                $this->assign('askPage','other');
                // 判断访问用户与登录用户的关系
                $this->assign('relationToMe',$this->getRelation($uid));
            }
            // 用$uid实例化查询用户信息如果为空则用户不存在,报错跳回
            if ((M('user')->where('id ='.$uid)->find()) == null) {
                $this->error('不存在的用户!','',1);
                exit;
            }
            // 我的粉丝相关信息
            $fans = M('fans')->table('baidu_user u,baidu_fans f,baidu_user_info i')->field('u.name,u.id,i.nickname,i.exp,i.path,i.status,i.signature,i.sex,i.fans,i.faned')->where('f.uid ='.$uid.' AND u.id = f.fuid AND u.id = i.uid')->select();

            // 被我粉的人 相关信息
            $attentions = M('fans')->table('baidu_user u,baidu_fans f,baidu_user_info i')->field('u.name,u.id,i.nickname,i.exp,i.path,i.status,i.signature,i.sex,i.fans,i.faned')->where('f.fuid ='.$uid.' AND u.id = f.uid AND u.id = i.uid')->select();
            // for 循环获得与当前登录用户的关系 并截取个性签名的
            for ($i=0; $i < count($fans); $i++) { 
                $fans[$i]['relation'] = $this->getRelationZh($this->getRelation($fans[$i]['id']));
                $fans[$i]['relation_num'] = $this->getRelation($fans[$i]['id']);
                $fans[$i]['level'] = $this->getUserLevelNum($fans[$i]['exp']);
                $fans[$i]['reward'] = $this->getUserLevel($fans[$i]['level']);
            }
            for ($i=0; $i < count($attentions); $i++) { 
                $attentions[$i]['relation'] = $this->getRelationZh($this->getRelation($attentions[$i]['id']));
                $attentions[$i]['relation_num'] = $this->getRelation($attentions[$i]['id']);
                $attentions[$i]['level'] = $this->getUserLevelNum($attentions[$i]['exp']);
                $attentions[$i]['reward'] = $this->getUserLevel($attentions[$i]['level']);
            }
            
            // 粉丝数,关注数,发布经验数
            $this->assign('fans_number',count($fans));
            $this->assign('att_number',count($attentions));
            $this->assign('exp_num',count(M('experience')->where('uid ='.$_SESSION['user']['uid'])->count()));
            $this->assign('fans',$fans);
            $this->assign('attentions',$attentions);
            // 用户头像信息
            $photo_info = M('user_info')->where('uid =' .$uid)->find();
            
            $this->assign('nickname',$photo_info['nickname']);
            // 获得用户信息
            $user = M('user');
            $user_info = $user->table('baidu_user u,baidu_user_info ui')->field('u.name as uname,u.phone as uphone,u.email as uemail,u.time as utime,ui.signature as uisignature,ui.nickname as uinickname,ui.sex as uisex,ui.gold as uigold,ui.fans as uifans,ui.status as uistatus,ui.exp as uiexp,ui.age as uiage,ui.path as path,ui.thumbpath as thumbpath,ui.faned as faned')->where('u.id=ui.uid AND u.id= '.$uid )->select();
            $user_info = $user_info[0];
            $user_info['exp_css'] =$user_info['uiexp'] - 100* ($this->getUserLevelNum($user_info['uiexp']) -1);
            // 遍历发布经验信息
            $articles = M('experience')->where('uid = '.$uid)->order('id DESC')->select();
            $count = count($articles);
            $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(10)
            $Page->lastSuffix = false;
            $Page->setConfig('prev','上一页');
            $Page->setConfig('next','下一页');
            $Page->setConfig('first','首页');
            $Page->setConfig('last','尾页');
            $show = $Page->show();// 分页显示输出
            $articles = M('experience')->field('title,id,create_time')->where('uid = '.$uid)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

            for ($i=0; $i < count($articles); $i++) { 
                $articles[$i]['create_time'] = date('Y-m-d H:i:s',$articles[$i]['create_time']);
                $articles[$i]['new_title'] = mb_substr($articles[$i]['title'] , 0 ,24,'utf-8').'......';
            }
            $this->assign('articles',$articles);
            $this->assign('page',$show);
            /*经验相关结束*/


            /*遍历用户收藏过的文章*/
            $zan = M('experience');

            $zans = $zan->table('baidu_collect z,baidu_experience e')->field('e.title as title,e._s_picture as pic,e.id')->where('z.uid ='.$uid.' AND e.id = z.eid')->order('z.id DESC')->limit(0,9)->select();
            // 循环截取title
            for ($i=0; $i < count($zans); $i++) { 
                $zans[$i]['short_title'] = mb_substr($zans[$i]['title'], 0,10).'...';   
            }
            $this->assign('zans',$zans);
            /*收藏相关结束*/
            $exp = $user_info['uiexp'];
            $level = $this->getUserLevelNum($exp);
            $this->assign('design',$this->getUserLevel($level));
            $exp = $exp%100;
            $user_info['level'] = $level;
            $user_info['exp'] = $exp;
            if ($user_info['nickname'] === null) {
                $user_info['uinickname'] = $user_info['uname'];
            }
            $this->assign('user_info',$user_info);
            $this->assign('questions',$questions);
            $this->assign('anwsers',$anwsers);
            $this->display('Pers/pers');
        }else{
            $this->error('请先登录',U('Home/Login/index'),1);
        }
        
    }
    // 搜索下拉框
    public function search()
    {
        if (!IS_AJAX) {
            $this->error('亲,请不要胡来好吗....');
        }
        $user = M('user');
        if ($_POST['uname'] =='') {
            exit;
        }
        $where['name'] = array('like','%'.$_POST['uname'].'%');
        $result = $user->field('id,name')->where($where)->select();
        json_encode($result);
        $this->ajaxReturn($result);
    }

    //  搜索
    public function searchGo()
    {
        if (empty($_SESSION['user']) ) {
            $this->error('还没有登录呢,亲!',U('Login/index',2));
        } elseif (empty($_POST['uname'])) {
            $this->error('您在搞笑吗?亲!','',2);
        }
        $user = M('user');
        $data = $user->field('id')->where('name ='.$_POST['uname'])->select();
        if (empty($data)) {
            $this->error('不存在的用户');
        } else{
            $this->success('恭喜您,访问成功',U('Pers/index').'?uid='.$data['id'],1);
        }
    }

    // 获得用户lv等级
    public function getUserLevelNum($exp)
    {
        return (($exp - $exp%100)/100)+1;
    }

    //获得用户等级
    public function getUserLevel($level)
    {
        switch ($level) {
                case 1:
                    return '初学乍练';
                    break;
                case 2:
                    return '登堂入室';
                    break;
                case 3:
                    return '初窥堂奥';
                    break;
                case 4:
                    return '略有小成';
                    break;
                case 5:
                    return '渐入佳境';
                    break;
                case 6:
                    return '炉火纯青';
                    break;
                case 7:
                    return '自成一派';
                    break;
                case 8:
                    return '功行圆满';
                    break;
                case 9:
                    return '登峰造极';
                    break;
                default:
                    return '神功绝世';
                    break;
            }
    }

    // 获得obj用户与登录用户的关系
    public function getRelation($obj)
    {
        $myid = $_SESSION['user']['uid'];
        $info = M('fans');
        $aboutMe = $info->where('uid ='.$myid)->select();
        $aboutObj = $info->where('uid ='.$obj)->select();
        $myfansid = array(); // 我的粉丝们的ID
        $hisfansid = array(); // 对象的粉丝们的ID
        for ($i=0; $i < count($aboutMe); $i++) { 
            $myfansid[] = $aboutMe[($i)]['fuid'];
        }
        for ($i=0; $i < count($aboutObj); $i++) { 
            $hisfansid[] = $aboutObj[$i]['fuid'];
        }

        $aboutObj = $info->where('uid ='.$obj)->select();
        if (in_array($myid, $hisfansid) && in_array($obj, $myfansid)) {
            $relation = 1; // 互相关注
        }elseif (in_array($obj, $myfansid)) {
            $relation = 2; //他只关注了我
        }elseif (in_array($myid, $hisfansid)) {
            $relation = 3;// 我只关注了他
        }else{
            $relation = 4;//暂无关系
        }
        
        return $relation;
    }

    // 将用户关系转为字串
    public function getRelationZh($relation)
    {
        switch ($relation) {
            case 1:
                return '互相关注!';
                break;
            case 2:
                return '他关注了我!';
                break;
            case 3:
                return '我关注了他!';
                break;
            case 4:
                return '暂无关系!';
                break;
        }
    }

    // 用户信息编辑
    public function edit()
    {
        if (empty($_SESSION['user'])) {
            $this->redirect('请先登录','Index/index');
        }
        //判断 有无传递POST
        if (empty($_POST)) {
            $this->error('请完善数据!');
            exit;
        }

        $uid = $_SESSION['user']['uid'];
        $data1['phone'] = $_POST['phone'];
        $data1['email'] = $_POST['email'];
        $data2['nickname'] = $_POST['username'];
        $data2['age'] = $_POST['age'];
        $data2['sex'] = $_POST['sex'];
        $data2['signature'] = $_POST['per'];
        $user = D('user');
        $user_info = D('user_info');

        
        if (!$user->create()) {
            $this->error( $user->getError() );
        }
        
        if (!$user_info->create()) {
            $this->error( $user_info->getError() );
        }elseif (false !== $user_info->where('uid ='.$uid)->save($data2)) {

            if (false !== $user->where('id = '.$uid)->save($data1)) {
                $this->success('编辑成功','index',1);
            } else {
                $this->error('用户基本信息编辑失败!');
            }
        }else{
            $this->error('用户扩展信息编辑失败');
        }
        
        
        
    }
    

    // 关注
    public function addAttention()
    {
        if (!IS_AJAX) {
            $this->error('亲,请不要胡来好吗....');
        }
        $uid = $_GET['uid'];
        $relation = D('fans');
        $data['uid'] = $uid;
        $data['fuid'] = $_SESSION['user']['uid'];
        $user_info = M('user_info');


        if ($data['uid'] == $data['fuid']) {
            $this->error('自己不可以关注自己啊亲~');
            exit;
        }
        //被关注的人粉丝数+1 关注者关注数faned+1
        $user_info->where('uid ='.$data['uid'])->setInc('fans');
        //
        $user_info->where('uid ='.$data['fuid'])->setInc('faned');
        // 两者数据都更新成功则执行下一步
        
        $relation->data($data)->add();
        $fans_num = count($faned_num = M('fans')->where('fuid ='.$data['fuid'])->select());
        $this->ajaxReturn($fans_num);

        
        

    }

    // 取消关注
    public function removeAttention()
    {
        if (!IS_AJAX) {
            $this->error('亲,请不要胡来好吗....');
        }
        $uid = $_GET['uid'];
        $relation = M('fans');
        $data['uid'] = $uid;
        $data['fuid'] = $_SESSION['user']['uid'];
        $user_info = M('user_info');
        // 被取消关注的人粉丝数-1
        $user_info->where('uid ='.$data['uid'])->setDec('fans');
        //关注者关注数faned-1
        $user_info->where('uid ='.$data['fuid'])->setDec('faned');
        // 两者数据都更新成功则执行下一步
        $relation->where($data)->delete();
        $fans_num = count($faned_num = M('fans')->where('fuid ='.$data['fuid'])->select());
        $this->ajaxReturn($fans_num);
    }


    // 删除个人经验
    public function delete()
    {
        if (!IS_AJAX) {
            $this->error('亲,请不要胡来好吗....');
        }
        // 利用session判断,只能删除自己的经验,不能删除别人的
        $myExps = M('experience');
        $data['uid'] = $_SESSION['user']['uid'];
        $data['id'] = $_GET['id'];
        // 如果找不到则停止
        $info = $myExps->where($data)->find();
        if (!$info) {
            exit;
        } else{
            // 删除相关图片
            unlink($_SERVER["DOCUMENT_ROOT"].$info['picture']);
            unlink($_SERVER["DOCUMENT_ROOT"].$info['_s_picture']);
            unlink($_SERVER["DOCUMENT_ROOT"].$info['_l_picture']);
        }
        // 删除失败则停止后续
        if (!$myExps->where($data)->delete()) {
            exit;
        } else{
            M('collect')->where(array('eid'=>array('eq',$_GET['id'])))->delete();
            M('comment')->where(array('eid'=>array('eq',$_GET['id'])))->delete();
            M('reply')->where(array('eid'=>array('eq',$_GET['id'])))->delete();
        }

        $this->ajaxReturn('恭喜您删除成功!');
    }


    // 用金币加阅读量
    public function toHot()
    {
        if (!IS_AJAX) {
            $this->error('亲,请不要胡来好吗....');
        }
        // 先查询金币>=50?
        if ( M('user_info')->field('gold')->where('uid ='.$_SESSION['user']['uid'])->find()['gold']<50) {
            json_encode($data['msg']='金币余额不足!');
            $this->ajaxReturn($data);
            exit;
        }
        // 文章阅读量+50 用户金币-50
        if (!M('experience')->where('id ='.$_GET['id'])->setInc('reader',50) || !M('user_info')->where('uid ='.$_SESSION['user']['uid'])->setDec('gold',50) ) {
            $this->ajaxReturn('加热失败!');
        }else{
            $gold = M('user_info')->field('gold')->where('uid ='.$_SESSION['user']['uid'])->find()['gold'];
            $data['gold'] = $gold;
            $data['msg'] = '已花费50金币为您的文章增加了50的阅读量~';
            $data['less'] = '-50';
            json_encode($data);
            $this->ajaxReturn($data);
        }
    }

    // 用户头像更新
    public function photo()
    {
        //判断 有无传递POST
        if ($_FILES['newPhoto']['error'] == 4) {
            $this->error('选择一张图片!');
            exit;
        } elseif (empty($_POST)) {
            $this->error('非法操作!');
            exit;
        } else{
            $user_info = M('user_info');
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize = 3145728 ;// 设置附件上传大小
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath = './Public/photos/'; // 设置附件上传根目录
            $upload->savePath = ''; // 设置附件上传（子）目录
            $upload->saveName = 'user'.mt_rand(0,9999999999).time();
            $upload->autoSub = false;// 不使用子目录
            $upload->replace = true;// 用新的photo覆盖旧的photo
            $info = $upload->upload()['newPhoto'];// 上传文件
            // 生成两个路径
            $paths = array();
            $paths['path'] = '/Public/photos/'.$info['savepath'].$info['savename'];
            $paths['thumbpath'] = '/Public/photos/'.$info['savepath'].'thumb'.$upload->saveName.'.'.$info['ext'];

            // 处理图片,生成一个thumb缩略图
            $image = new \Think\Image();
            $image->open('.'.$paths['path']);
            $image->thumb(80, 80)->save('./'.$paths['thumbpath']);
            $paths['uid'] = $_SESSION['user']['uid'];
            if(!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
                exit;
            }else{
                $user_info->create();
                $user_info->where('uid = '.$paths['uid'])->save($paths);
                //如果数据库数据更新成功
                $this->success('上传成功！');
            }
        }
    }
}